require! {
  \fs-extra : fs
}
require! <[
  ./Git.ls
  ./argv.ls
  ./log
  chalk
  path
]>

module.exports = (dir)!~>
  if not await fs.exists dir
    return

  {mtimeMs} = await fs.stat dir
  day = (new Date() - mtimeMs)/86400000

  git = Git(dir)
  if argv.upgrade or (
    day > (parseFloat(process.env.DURATION_UPGRADE_6DU) or 7)
  )
    origin = await git.remote-origin!
    if not origin?.startsWith('https://')
      log "ignore origin #origin"
      return
    fetch = git.fetch!
    return ~>
      log.start "检查更新 #{chalk.blue(origin)}"
      await fetch
      version = await git.version-max!
      if version
        hash-now = await git.resolve-ref \HEAD
        hash-latest = await git.resolve-ref \v + version
        pjson = path.join(
          dir
          \package.json
        )
        if await fs.exists pjson
          {name, homepage} = require pjson
        else
          name = origin

        if hash-now == hash-latest
          log.done "已是最新 "+chalk.gray("#{name} v#version\n")
        else
          log "本次更新如下 :\n"

          for [date, msg] in await git.update-log!
            pos = msg.indexOf(' ')
            console.log chalk.gray "#date #{msg.slice(0, pos)}"
            console.log chalk.greenBright(msg.slice(pos+1))
          await git.checkout hash-latest
          npm-install = require(\./npm-install.ls)
          await npm-install dir
          for d in await fs.readdir(dir)
            d = path.join(dir,d)
            if fs.lstatSync(d).isDirectory!
              if await fs.exists(path.join(d,\package.json))
                await npm-install d
          log.done "成功升级到 #version\n"
          if homepage
            log.done "访问以下链接 , 了解更新详情"
            console.log "\n👉 #{chalk.underline.yellowBright homepage}\n"
